package com.lagou.rocketmq.listener;

import com.alibaba.fastjson.JSON;
import com.lagou.rocketmq.entity.Order;
import com.lagou.rocketmq.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(topic = "timeout_order", consumerGroup = "consumer_group_timeout_order")
public class TimeoutOrderListener implements RocketMQListener<String> {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(String message) {
        Order order = JSON.parseObject(message, Order.class);

        Integer status = orderService.getStatus(order.getId());

        if(status != null && status == 0) {
            orderService.cancelOrder(order.getId());

            //恢复redis库存数据
            Integer productStock = (Integer) redisTemplate.opsForValue().get(order.getProductId());
            redisTemplate.opsForValue().set(order.getProductId(), productStock + 1);
        }
    }
}
